class MDict {
  instance = null;

  constructor(filePath) {
    // 初始化
    const that = this;
    // 下载mdx文件
    axios({
      method: "get",
      url: filePath,
      responseType: "blob",
    }).then((res) => {
      const { data: blob } = res;
      const file_mdx = new File([blob], "mdict.mdx");
      const fileList = [file_mdx];
      require([
        "jquery",
        "mdict-common",
        "mdict-parser",
        "mdict-renderer",
        "selectize",
      ], function ($, MCommon, MParser, MRenderer, Selectize) {
        MParser(fileList).then((resources) => {
          const mdict = MRenderer(resources);
          const description =
            (resources["mdx"] || resources["mdd"]).value().description ||
            "** no description **";
          that.instance = Object.assign(mdict, { description });
        });
      });
    });
  }

  /**
   * 查找单词（获取详情）
   * @param {*} word 单词
   * @returns
   */
  lookup(word, offset) {
    return new Promise((resolve) => {
      if (!this.instance) {
        resolve(null);
        return;
      }

      console.log("lookup =>", word + "");
      this.instance.lookup(word, offset).then(function ($content) {
        resolve($content);

        $("#definition").empty().append($content.contents());
      });
    });
  }

  /**
   * 检索单词，返回数组
   * @param {*} keyword 关键词
   * @returns
   */
  search(keyword) {
    return new Promise((resolve) => {
      if (!this.instance) {
        resolve([]);
        return;
      }

      this.instance
        .search({ phrase: keyword, max: 5000 })
        .then(function (list) {
          if (Array.isArray(list)) {
            resolve(
              list.map(function (v) {
                return { word: v, offset: v.offset };
              })
            );
          } else {
            resolve([]);
          }
        });
    });
  }

  /**
   * 发音，返回音频路径
   * @param {*} word 单词
   */
  speak(word) {
    return `https://aizjtest.sndtech.cn/speak/${word}.mp3`;
  }
}

window.MDict = MDict;
